<!DOCTYPE html>
<html lang="zh-cn">
  <head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"
    />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <title>2. 两数相加</title>
  </head>
  <body>
    <!-- start -->
    <div>https://leetcode.cn/problems/add-two-numbers/description/</div>
    <!-- end -->
  </body>
  <!-- js start -->
  <script type="text/javascript">
    /**
     * Definition for singly-linked list.
     * function ListNode(val, next) {
     *     this.val = (val===undefined ? 0 : val)
     *     this.next = (next===undefined ? null : next)
     * }
     */
    /**
     * @param {ListNode} l1
     * @param {ListNode} l2
     * @return {ListNode}
     */
    var addTwoNumbers = function (l1, l2) {
      let resultArr = addVal(l1, l2);

      let lastNode = null;
      for (let i = 0; i < resultArr.length; i++) {
        const val = resultArr[i];

        lastNode = {
          val: val,
          next: lastNode,
        };
      }

      return lastNode;
    };

    function addVal(l1, l2, resArr = []) {
      if (!l1 && !l2) return resArr;

      let l1Val = l1 ? l1.val : 0;
      let l2Val = l2 ? l2.val : 0;

      let itemVal = l1Val + l2Val;
      resArr.push(itemVal >= 10 ? itemVal - 10 : itemVal);
      return addVal((l1 && l1.next) || null, (l2 && l2.next) || null, resArr);
    }
  </script>
</html>
